import { goodsList, goodsCount } from '../../../request/api'
const state = {
    goodslist: [],//商品列表
    size: 3,
    page: 1,
    count: 5,
}

const mutations = {
    // 修改商品列表
    GOODS_LIST(state, payload) {
        state.goodslist = payload;
    },
    // 修改总条数
    GOODS_SIZE(state, payload) {
        state.count = payload;
    },
    // 切换页码 
    CHANGE_PAGE(state, payload) {
        state.page = payload;
    }
}
const actions = {
    // 获取商品列表
    goodsListAction(context) {
        goodsList({
            size: context.state.size,
            page: context.state.page
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                context.commit('GOODS_LIST', res.list)
                // 删除非第一页且所有数据时 或显示暂无数据
                if (context.state.page != 1 && res.list == null) {
                    // 更改页码 并且重新渲染视图
                    context.dispatch('changePage');
                }
            }
        })
    },
    // 获取总条数
    goodsCountActions({ commit }) {
        goodsCount().then(res => {
            if (res.code == 200) {
                commit('GOODS_SIZE', res.list[0].total)
            }
        })
    },
    // 切换页码 
    changePage(context, payload) {
        context.commit('CHANGE_PAGE', payload);
        // 重新渲染视图
        context.dispatch('goodsListAction')
    }
}

const getters = {
    getGoodsList(state) {
        return state.goodslist
    },
    getSize(state) {
        return state.size;
    },
    getCount(state) {
        return state.count
    }
}

export default {
    state, mutations, actions, getters, namespaced: true

}